﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
using System.IO;

namespace CashNote
{
    class EncryptString
    {
        #region DES加密字符串
        /// <summary> 
        /// 加密字符串 
        /// 注意:密钥必须为８位 
        /// </summary> 
        /// <param name="strText">字符串</param> 
        public string DesEncrypt(string strText)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                string encryptKey = "yangsiyu";                   //密钥
                byKey = System.Text.Encoding.UTF8.GetBytes(encryptKey);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                return Convert.ToBase64String(ms.ToArray());

            }
            catch
            {
            }
            return strText;
        }
        #endregion

        #region DES解密字符串
        /// <summary> 
        /// 解密字符串 
        /// </summary> 
        /// <param name="inputString">加了密的字符串</param> 
        public string DesDecrypt(string inputString)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[inputString.Length];
            try
            {
                string decryptKey = "yangsiyu";
                byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                inputByteArray = Convert.FromBase64String(inputString);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                return encoding.GetString(ms.ToArray());
            }
            catch
            {

            }

            return inputString;
        }
        #endregion
    }
}